<?php

class admin_model extends CI_Model
{
    public function __construct()
    {
        $this->load->database();
    }
    
    public function get_login_info_by_username($username)
    {
        $query=$this->db->get_where('login',array('userName'=>$username));
        return $query->row_array();
    }
    
    public function get_user()
    {
        $this->db->select("*");
        $query = $this->db->get('user');
        return $query->result_array();
    }
    
    public function get_user_by_id($id)
    {
        $query=$this->db->get_where('user',array('id'=>$id));
        return $query->row_array();
    }
    
    
    public function addUser()
    {
        $data['userName'] = $this->input->post('User',TRUE);
        $data['passwd'] = md5(md5(md5($this->input->post('password1',TRUE))));
        if ($this->is_exist($data['userName'])!=null)
        {
            return false;
        }
        else
        {
            $this->db->insert('user',$data);
            return true;
        }
    }
    
    public function is_exist($userName)
    {
        $query=$this->db->get_where('user',array('userName'=>$userName));
        return $query->row_array();
    }
    
    public function is_right($pw)
    {
        $query=$this->db->get_where('user',array('passwd'=>$userName));
        return $query->row_array();
    }
    
    public function update_by_userName($role)
    {
        $data['passwd'] = md5(md5(md5($this->input->post('password1',TRUE))));
        if ($role!='admin')
        {
            $data['userName'] = $this->input->post('User',TRUE);
            $this->db->where('userName', $data['userName']);
            $this->db->update('user', $data);
            return $this->db->affected_rows();
        }
        else 
        {
            if ($this->is_right($data['passwd']))
            {
                $this->db->where('userName', 'admin');
                $this->db->update('login', $data);
                return true;
            }
            else
            {
                return FALSE;
            }
        }
        
    }
}